<?php

// +----------------------------------------------------------------------
// | DyCode [ WE CAN DO IT JUST dy ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://DyCode.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

namespace dy;


class Controller
{
    /**
     * 应用实例
     * @var \dy\App
     */
    protected $app;

    /**
     * Request实例
     * @var \dy\Request
     */
    protected $request;

    /**
     * 构造方法
     * @access public
     */
    public function __construct(App $app = null)
    {
        $this->app     = $app ?: Container::get('app');
        $this->request = $this->app['request'];

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {

    }

    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param  string    $url 跳转的URL地址
     * @param  mixed     $msg 提示信息
     * @param  integer   $wait 跳转等待时间
     * @return void
     */
    protected function success($url, $msg = '', $wait = 3)
    {
        $this->redirect($url, $msg, $wait, 1);
    }

    /**
     * 操作错误跳转的快捷方法
     * @access protected
     * @param  mixed     $msg 提示信息
     * @param  string    $url 跳转的URL地址
     * @param  mixed     $data 返回的数据
     * @param  integer   $wait 跳转等待时间
     * @param  array     $header 发送的Header信息
     * @return void
     */
    protected function error($url, $msg = '', $wait = 3)
    {
        $this->redirect($url, $msg, $wait, 0);
    }

    /**
     * 返回封装后的API数据到客户端
     * @access protected
     * @param  mixed     $data 要返回的数据
     * @param  integer   $code 返回的code
     * @param  mixed     $msg 提示信息
     * @return void
     */
    protected function result($data, $code = 0, $msg = '')
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => time(),
            'data' => $data,
        ];

        header('content-type:application/json');

        exit(json_encode($result, JSON_UNESCAPED_UNICODE));
    }

    /**
     * URL重定向
     * @param string $url   跳转的URL表达式
     * @param string $msg   提示消息
     * @param int $wait     跳转等待时间
     * @param int $code     1成功,0失败
     * @return void
     */
    protected function redirect($url, $msg = '', $wait = 0, $code = 302)
    {
        if ($wait == 0){
            header("Location:$url");
        } else {
            include __DIR__ . "/../tpl/dispatch_jump.tpl";
        }

        exit;
    }
}
